package com.szh.lenovo0520;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    private EditText mainUsername;
    private EditText mainUserPwd;
    private Button mainBtnLogin;
    MyDBHelper helper;
    SQLiteDatabase db;
    DBService.MyBinder binder;
    private MyConnection myConnection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainUsername = (EditText) findViewById(R.id.main_username);
        mainUserPwd = (EditText) findViewById(R.id.main_userPwd);
        mainBtnLogin = (Button) findViewById(R.id.main_btnLogin);
        helper=new MyDBHelper(this);
        db=helper.getWritableDatabase();
        mainBtnLogin.setOnClickListener(this);
        Intent intent = new Intent(MainActivity.this, DBService.class);
        myConnection = new MyConnection();
        bindService(intent,myConnection, Context.BIND_AUTO_CREATE);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.main_btnLogin:
                String name = mainUsername.getText().toString().trim();
                String pwd = mainUserPwd.getText().toString().trim();
                Log.d(TAG, "name: "+name);
                Log.d(TAG, "pwd: "+pwd);
//                Cursor user = db.query("user", null, "username=?", new String[]{name}, null, null, null);
//                user.moveToNext();
//                String userPwd = user.getString(user.getColumnIndex("userPwd"));
//                Log.d(TAG, "onCreate: "+userPwd);
                binder.CallQueryInfo(name,pwd);
                break;
        }
    }

    private class MyConnection implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected: ");
            binder= (DBService.MyBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "onServiceDisconnected: ");
            unbindService(myConnection);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(myConnection);
        Log.d(TAG, "onServiceDisconnected: ");
    }
}
